package com.innovation.chengzhangriji.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.PublicPhotoTheme;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.http.ThemeGetResponse;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.innovation.chengzhangriji.ui.widget.CuteExtraTitleToolbar;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.ThemeItemDecoration;
import com.innovation.chengzhangriji.ui.widget.ThemesAdapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public abstract class BaseTimelinePhotoAndCameraActivity extends BaseCameraActivity implements CuteToolbar.OnClickCuteToolbarListener {

    private static final int MAX_NUMBER = 9;

    private CuteExtraTitleToolbar mCuteToolbar;

    private View mThemeTopLine;

    private RecyclerView mThemesView;

    private CuteEditText mEditInput;

    private ThemesAdapter mThemesAdapter;

    private int mNumber;

    private boolean send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView();
        setupLayout();
        queryThemes();
    }

    @Override
    protected void noCamera() {
        tipShow("您的设备不支持该功能");
        super.noCamera();
    }

    @Override
    public void onClickLeft() {
        finish();
    }

    @Override
    public void onClickRight() {
        if (send) {
            return;
        }
        send = true;
        Intent returnIntent = new Intent();
        Bundle bundle = new Bundle();
        String theme = getTimelineTheme();
        if (TextUtils.isEmpty(theme)) {
            bundle.putString("theme", null);
        } else {
            bundle.putString("theme", theme);
        }
        bundle.putString("text", "" + getTimelineText());

        int length = getTimelineUrls().length;
        for (int i = 0; i < length; i++) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(getTimelineUrls()[i], options);
            options.inSampleSize = calculateInSampleSize(options, 640, 480);
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inJustDecodeBounds = false;
            Bitmap bmp = BitmapFactory.decodeFile(getTimelineUrls()[i], options);
            try {
                if(bmp == null) {
                    tipShow("图片错误，请重新选择");
                    return;
                }
                File file = new File(getTimelineUrls()[i]);
                FileOutputStream fOut = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.JPEG, 75, fOut);
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(bmp != null && !bmp.isRecycled()) {
                    bmp.recycle();
                }
                bmp = null;
            }
        }

        bundle.putStringArray("urls", getTimelineUrls());
        returnIntent.putExtras(bundle);
        setResult(RESULT_OK, returnIntent);
        finish();
    }

    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    protected abstract void setContentView();

    protected void addPhoto() {
        if (mNumber >= MAX_NUMBER) {
            return;
        }
        mNumber++;
        mCuteToolbar.setTextExtraTitleText(mNumber + "/" + MAX_NUMBER);
    }

    protected void removePhoto() {
        if (mNumber <= 0) {
            return;
        }
        mNumber--;
        mCuteToolbar.setTextExtraTitleText(mNumber + "/" + MAX_NUMBER);
    }

    protected final String getTimelineText() {
        return mEditInput.getText().toString();
    }

    protected final String getTimelineTheme() {
        return mThemesAdapter.getTheme();
    }

    protected abstract String[] getTimelineUrls();

    private void setupLayout() {
        mCuteToolbar = (CuteExtraTitleToolbar) findViewById(R.id.toolbar);
        mCuteToolbar.setTextExtraTitleText(mNumber + "/" + MAX_NUMBER);
        mCuteToolbar.setOnClickCuteToolbarListener(this);
        mThemeTopLine = findViewById(R.id.top_line);
        mThemesView = (RecyclerView) findViewById(R.id.themes_view);
        mThemesView.addItemDecoration(new ThemeItemDecoration());
        GridLayoutManager themesGridLayoutManager = new GridLayoutManager(this, 1, LinearLayoutManager.HORIZONTAL, false);
        mThemesView.setLayoutManager(themesGridLayoutManager);
        mThemesAdapter = new ThemesAdapter();
        mThemesView.setAdapter(mThemesAdapter);
        mEditInput = (CuteEditText) findViewById(R.id.edit_milestone);
    }

    private void queryThemes() {
        PublicPhotoTheme[] photoThemes = DatabaseManager.getInstance(this).queryPhotoThemes();
        if (photoThemes == null) {
            requestThemes();
        } else {
            int length = photoThemes.length;
            String[] themes = new String[length];
            for (int i = 0; i < length; i++) {
                themes[i] = photoThemes[i].getTheme();
            }
            updateThemesUI(themes);
        }
    }

    private void requestThemes() {
        LoginInfo login = Config.getLoginInfo(this);
        String phone = login.getPhone();
        String token = login.getToken().getAccessToken();
        Client.requestThemeGet(this, phone, token, new ResponseHandler() {
            @Override
            public void onInnovationSuccess(JsonElement value) {
                ThemeGetResponse response = get(value.toString(), ThemeGetResponse.class);
                insertThemes(response.getThemes());
                updateThemesUI(response.getThemes());
            }
        }, null);
    }

    private void updateThemesUI(String[] themes) {
        mThemesView.setVisibility(View.VISIBLE);
        mThemeTopLine.setVisibility(View.VISIBLE);
        mThemesAdapter.addThemes(themes);
    }

    private void insertThemes(String[] themes) {
        DatabaseManager.getInstance(this).insertPhotoThemes(themes);
    }
}
